const express = require('express')
const route = express.Router()
const advModel = require('../db/model/advModel')
//引入权限校验中间件
const isLoginMiddle = require("../middleware/isLoginMiddle")

const path = require('path')
const fs = require('fs')

route.delete('/deleteAdv', isLoginMiddle, async (req, res) => {





  const { _id } = req.query
  console.log(req.query);


  //在后端upload中删除图片
  //根据_id在数据库中找到对应advHref的图片,在文件夹中删除文件
  try {
    const { advHref } = await advModel.findOne({ _id })
    console.log(advHref);
    console.log(advHref.split('/')[2]);
    const imgName = advHref.split('/')[2]
    fs.unlink(path.resolve(__dirname, '../upload', imgName), () => {
      console.log('删除图片成功');
    })
  } catch (e) {
    console.log('删除图片时出现错误' + e.message);
    return res.send({
      code: 10001,
      msg: '删除图片时出现问题' + e.message,
      data: null
    })
  }

  //在数据库中删除图片
  try {
    const deleteResult = await advModel.deleteOne({ _id })
    res.send({
      code: 10000,
      msg: '删除广告成功',
      data: null
    })
  } catch (e) {
    console.log('删除广告时出现问题' + e.message);
    res.send({
      code: 10001,
      msg: '删除图广告时出现问题' + e.message,
      data: null
    })
  }


})

module.exports = route